// Copyright [2020] <unknown>
#include <bits/stdc++.h>
using namespace std;
// #define ONLINE_JUDGE
#ifndef ONLINE_JUDGE
#define dbg(x...) { cerr << "\033[32;1m" << #x << " -> "; err(x); }
void err() { cerr << "\033[39;0m" << endl; }
template<typename T, typename... A>
void err(T a, A... x) { cerr << a << ' '; err(x...); }
#else
#define dbg(...)
#endif

#define sz(x) ((int)x.size())

typedef long long LL;

const int N = 2e5+50;

int p[N], c[N];

int check(vector<int> &a) {
    static bool vis[N];
    int n = a.size();
    for (int i=1; i<=n; ++i) {
        if (n % i == 0) {
            memset(vis, 0, sizeof(bool) * i);
            for (int j=i; j<n; ++j) {
                if (c[a[j]] != c[a[j%i]])
                    vis[j%i] = 1;
            }

            for (int j=0; j<i; ++j)
                if (!vis[j])
                    return i;
        }   
    }
    return -1;
}
int n;
int main(int argc, char const *argv[]) {
    // code
    int t;
    scanf("%d", &t);
    for (int kk=0; kk<t; ++kk) {
        scanf("%d", &n);
        for (int i=1; i<=n; ++i)
            scanf("%d", &p[i]);
        for (int i=1; i<=n; ++i)
            scanf("%d", &c[i]);

        static bool vis[N];
        int ans = 1e9;
        memset(vis, 0, sizeof(bool) * (n + 1));
        for (int i=1; i<=n; ++i) {
            if (!vis[i]) {
                vector<int> path;
                path.push_back(i);
                vis[i] = 1;
                for (int now=p[i]; !vis[now]; now=p[now]) {
                    path.push_back(now);
                    vis[now] = 1;
                }
                int tans = check(path);
                if (~tans)
                    ans = min(ans, tans);
            }   
        }

        printf("%d\n", ans);

    }
    return 0;
}
